<script lang="ts" setup>
import type { TreeNodeData } from 'element-plus/es/components/tree/src/tree.type';
import type { Recordable } from '@vben/types';
import type { RoleApi } from '#/api/system/role';

import { computed, ref, watch, nextTick } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { ElTree, ElLoading, ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { getMenuTree } from '#/api/system/menu';
import { createRole, getRoleById, updateRole } from '#/api/system/role';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

const emits = defineEmits(['success']);

const formData = ref<Partial<RoleApi.RoleItem>>({});
const treeRef = ref<any>();
// 是否为系统角色（只读）
const isSystemRole = ref(false);

const [Form, formApi] = useVbenForm({
  schema: useFormSchema(),
  showDefaultActions: false,
});

const permissions = ref<any[]>([]); // 权限列表
const selectedPermissions = ref<string[]>([]); // 选中的权限ID列表
const loadingPermissions = ref(false); // 添加加载状态

// 监听权限数据变化
watch(permissions, (newVal) => {
  // 权限数据变化时的处理
}, { immediate: true });



// 监听树形控件选择变化
const handleTreeCheck = (_: any, checked: { checkedKeys: string[], checkedNodes: any[] }) => {
  console.log('树形控件选择变化:', checked);
  selectedPermissions.value = checked.checkedKeys;
};

const id = ref();

/**
 * 加载角色详情
 */
async function loadRoleDetail(roleId: string) {
  try {
    const detail = await getRoleById(roleId);
    console.log('加载角色详情:', detail);
    // 设置选中的权限
    selectedPermissions.value = detail.permissionIds || [];
    // 等待下一个tick，确保树形控件已经渲染
    await nextTick();
    // 设置树的选中状态
    if (treeRef.value?.setCheckedKeys) {
      console.log('设置树形控件选中状态:', selectedPermissions.value);
      treeRef.value.setCheckedKeys(selectedPermissions.value);
    }
    return detail;
  } catch (error) {
    console.error('获取角色详情失败:', error);
    return null;
  }
}

/**
 * 保存角色（创建或更新）
 */
async function handleSaveRole() {
  const { valid } = await formApi.validate();
  if (!valid) return;

  // 获取表单数据
  const values = await formApi.getValues();
  console.log('表单数据:', values);
  console.log('选中的权限:', selectedPermissions.value);

  try {
    if (id.value) {
      // 获取当前角色详情，但只获取并发标记，不更新权限
      const roleDetail = await getRoleById(id.value);
      if (!roleDetail) {
        ElMessage.error($t('system.role.notFound'));
        return;
      }

      // 如果是系统角色，显示提示
      if (roleDetail.isSystem && (roleDetail.name !== values.name)) {
        ElMessage.warning($t('system.role.systemRoleHint'));
        return;
      }

      // 对于更新操作，添加id和并发标记
      const updateData: RoleApi.RoleUpdate = {
        id: id.value,
        name: values.name,
        description: values.description,
        concurrencyStamp: roleDetail.concurrencyStamp,
        permissionIds: selectedPermissions.value // 使用当前选中的权限
      };

      console.log('更新数据:', updateData);
      await updateRole(id.value, updateData);
      ElMessage.success($t('system.role.updateSuccess'));
    } else {
      // 创建操作直接使用表单数据
      const createData: RoleApi.RoleCreate = {
        name: values.name,
        description: values.description,
        isSystem: false, // 始终创建为自定义角色
        permissionIds: selectedPermissions.value
      };

      console.log('创建数据:', createData);
      await createRole(createData);
      ElMessage.success($t('system.role.createSuccess'));
    }

    emits('success');
    drawerApi.close();
  } catch (error: any) {
    console.error('保存角色失败:', error);
  }
}

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    drawerApi.lock();
    try {
      await handleSaveRole();
    } finally {
      drawerApi.unlock();
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<RoleApi.RoleItem>();
      formApi.resetForm();
      if (data) {
        formData.value = data;
        id.value = data.id;
        // 记录是否为系统角色
        isSystemRole.value = data.isSystem === true;

        // 如果是编辑模式,加载角色详情
        if (id.value) {
          loadRoleDetail(id.value);
        }

        // 如果是系统角色，禁用角色名称输入
        if (isSystemRole.value) {
          // 动态更新表单配置
          formApi.updateSchema([
            {
              fieldName: 'name',
              componentProps: {
                disabled: true,
              },
            },
            {
              fieldName: 'description',
              componentProps: {
                disabled: true,
              },
            },
          ]);
        }

        formApi.setValues(data);
      } else {
        id.value = undefined;
        isSystemRole.value = false;
        selectedPermissions.value = []; // 清空选中的权限
      }
      // 加载权限数据
      loadPermissions();
    }
  },
});

async function loadPermissions() {
  loadingPermissions.value = true;
  try {
    const res = await getMenuTree();
    permissions.value = res as unknown as any[];
  } catch (error) {
    console.error('加载权限数据失败:', error);
  } finally {
    loadingPermissions.value = false;
  }
}

const getDrawerTitle = computed(() => {
  return formData.value?.id
    ? $t('common.edit', [$t('system.role.name')])
    : $t('common.create', [$t('system.role.name')]);
});

function getNodeClass(node: Recordable<any>) {
  const classes: string[] = [];
  if (node.value?.type === 'button') {
    classes.push('inline-flex');
    if (node.index % 3 >= 1) {
      classes.push('!pl-0');
    }
  }
  return classes.join(' ');
}


</script>

<template>
  <Drawer :title="getDrawerTitle">
    <Form>
      <template #permissions="slotProps">
        <div v-loading="loadingPermissions" class="permission-tree">
          <el-tree
            ref="treeRef"
            :data="permissions"
            show-checkbox
            node-key="permissionId"
            :default-checked-keys="selectedPermissions"
            :props="{
              label: 'meta.title',
              children: 'children'
            }"
            @check="handleTreeCheck"
            v-bind="slotProps"
            class="permission-tree__content"
          >
            <template #default="{ node, data }">
              <span :class="getNodeClass(node)" class="permission-tree__node">
                <IconifyIcon
                  v-if="data.meta?.icon"
                  :icon="data.meta.icon"
                  class="permission-tree__icon mr-1"
                />
                <span class="permission-tree__label">{{ $t(data.meta.title) }}</span>
              </span>
            </template>
          </el-tree>
        </div>
      </template>
    </Form>
  </Drawer>
</template>

<style lang="scss" scoped>
.permission-tree {
  width: 100%;
  min-height: 400px;
  padding: 8px;
  background-color: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);

  &__content {
    width: 100%;
    height: 100%;
  }

  &__node {
    display: inline-flex;
    align-items: center;
    width: 100%;
  }

  &__icon {
    margin-right: 4px;
  }

  &__label {
    flex: 1;
  }
}

:deep(.el-tree) {
  background: transparent;
}

:deep(.el-tree-node) {
  &:focus > .el-tree-node__content {
    background-color: var(--el-tree-node-hover-bg-color);
  }
}

:deep(.el-tree-node__content) {
  height: 32px;
  padding: 0 8px;

  .tree-actions {
    display: none;
    margin-left: 20px;
  }

  &:hover {
    .tree-actions {
      display: flex;
      flex: auto;
      justify-content: flex-end;
      margin-left: 20px;
    }
  }
}
</style>
